//
//  DigitalExchangeViewController.m
//  HYApp
//
//  Created by Jianbo Cai on 2020/8/13.
//  Copyright © 2020 Unidax. All rights reserved.
//

#import "DigitalExchangeViewController.h"
#import "ChooseView.h"
#import "SheetView.h"
#import "DigitalExchangeTradeViewController.h"
#import "HYNetHelper.h"
#import "WalletsEntity.h"


@interface DigitalExchangeViewController ()

@property (weak, nonatomic) IBOutlet UIView *methodBgView;
@property (weak, nonatomic) IBOutlet UILabel *sellLabel;
@property (weak, nonatomic) IBOutlet UILabel *buyLabel;

@property (weak, nonatomic) IBOutlet UILabel *available;
@property (weak, nonatomic) IBOutlet UILabel *availableVaule;
@property (weak, nonatomic) IBOutlet UITextField *amountTextField;
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;
@property (weak, nonatomic) IBOutlet UILabel *coinType;
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;

@property (weak, nonatomic) IBOutlet UILabel *youSell;
@property (weak, nonatomic) IBOutlet UILabel *youBuy;
@property (weak, nonatomic) IBOutlet UILabel *methodTitle;

@property (weak, nonatomic) IBOutlet UILabel *tipsTitle;
@property (weak, nonatomic) IBOutlet UILabel *message;

@property (strong, nonatomic) ChooseView *chooseView;

@property (nonatomic, strong) ETHEntity *entity;

@property (nonatomic, strong) NSMutableArray *metadataAssets;

@end

@implementation DigitalExchangeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = JFMainLocalizedString(@"exchange.exchange");
    self.youSell.text = JFMainLocalizedString(@"exchange.from");
    self.youBuy.text = JFMainLocalizedString(@"exchange.to");
    self.methodTitle.text = JFMainLocalizedString(@"exchange.exchange");
    self.tipsTitle.text = JFMainLocalizedString(@"withdraw.tips");
    self.message.text = JFMainLocalizedString(@"exchange.algo-description");
    self.available.text = [NSString stringWithFormat:@"%@:", JFMainLocalizedString(@"exchange.availble")];
    self.totalLabel.text = JFMainLocalizedString(@"myAssets.total");
    self.amountTextField.placeholder = JFMainLocalizedString(@"deposit.please-enter-amount");
    [self.confirmButton setTitle:JFMainLocalizedString(@"exchange.get-quote") forState:UIControlStateNormal];
    
    [self.confirmButton setBackgroundImage:[UIImage imageWithColor:UIColorFromHex(0xCCCCCC) size:self.confirmButton.frame.size] forState:UIControlStateDisabled];
    [self.confirmButton setBackgroundImage:[UIImage imageWithColor:UIColorFromHex(0x70896A) size:self.confirmButton.frame.size] forState:UIControlStateNormal];
    self.confirmButton.enabled = NO;
    
    WEAKSELF
    self.chooseView = [[ChooseView alloc]initWithFrame:CGRectMake(15, 55, SCREEN_WIDTH - 30, 15) itemArray:@[@"By Amount", @"By Total"]];
    self.chooseView.vauleChange = ^(NSInteger selectIndex) {
        weakSelf.amountTextField.text = @"";
        [weakSelf setMethodType:selectIndex];
    };
    [self.methodBgView addSubview:self.chooseView];
    [self setMethodType:0];
    
    self.coinType.text = self.sellLabel.text = self.asset_address;
    if ([self.sellLabel.text isEqualToString:@"USD"]) {
        self.buyLabel.text = @"HKD";
    }
    [self requestData];
}

- (void)requestData {
    WEAKSELF;
    [HYNetHelper walletsMeta:self.walletsId callback:^(JFResultVo *resultVo) {
        if (!resultVo.errorNo) {
            weakSelf.entity = [ETHEntity yy_modelWithDictionary:resultVo.results];
            
            weakSelf.metadataAssets = [NSMutableArray arrayWithCapacity:5];
            for (BalanceListEntity *balance in self.entity.balance) {
                [weakSelf.metadataAssets addObject:balance.asset_address];
            }
            
            [weakSelf updateAvailableVaule];
        }
    }];
}

- (void)updateAvailableVaule {
    for (BalanceListEntity *balance in self.entity.balance) {
        if ([balance.asset_address isEqualToString:self.sellLabel.text]) {
            self.availableVaule.text = balance.balance_display;
        }
    }
}

- (void)setMethodType:(NSInteger)type {
    if (type == 0) {
        self.available.hidden = self.availableVaule.hidden = NO;
        self.totalLabel.text = JFMainLocalizedString(@"deal.amount");
        self.coinType.text = self.sellLabel.text;
    }else {
        self.available.hidden = self.availableVaule.hidden = YES;
        self.totalLabel.text = JFMainLocalizedString(@"myAssets.total");
        self.coinType.text = self.buyLabel.text;
    }
}

- (IBAction)editChangeAction:(id)sender {
    if (self.amountTextField.text.length > 0) {
        self.confirmButton.enabled = YES;
    }else {
        self.confirmButton.enabled = NO;
    }
}

- (IBAction)changeAction:(id)sender {
    NSString *originalBuy = self.buyLabel.text;
    self.buyLabel.text = self.sellLabel.text;
    self.coinType.text = self.sellLabel.text = originalBuy;
    [self updateAvailableVaule];
}


- (IBAction)changeSellAction:(id)sender {
    NSMutableArray *array = [NSMutableArray arrayWithArray:self.metadataAssets];
    [array removeObject:self.buyLabel.text];
    SheetView *view = [[[NSBundle mainBundle] loadNibNamed:@"SheetView" owner:nil options:nil] firstObject];
    view.frame = self.navigationController.view.bounds;
    view.index = [array indexOfObject:self.sellLabel.text];
    view.titleArray = array;
    WEAKSELF
    view.selectAction = ^(NSInteger index) {
        weakSelf.coinType.text = weakSelf.sellLabel.text = array[index];
        [weakSelf updateAvailableVaule];
    };
    [self.navigationController.view addSubview:view];
}

- (IBAction)changeBuyAction:(id)sender {
    NSMutableArray *array = [NSMutableArray arrayWithArray:self.metadataAssets];
    [array removeObject:self.sellLabel.text];
    SheetView *view = [[[NSBundle mainBundle] loadNibNamed:@"SheetView" owner:nil options:nil] firstObject];
    view.frame = self.navigationController.view.bounds;
    view.index = [array indexOfObject:self.buyLabel.text];
    view.titleArray = array;
    WEAKSELF
    view.selectAction = ^(NSInteger index) {
        weakSelf.buyLabel.text = array[index];
    };
    [self.navigationController.view addSubview:view];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 4:
        {
            CGRect rect = [self.message.text boundingRectWithSize:CGSizeMake(AWSCREEN_WIDTH - 32, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.message.font} context:nil];
            return rect.size.height + 110;
        }
            break;
        default:
            break;
    }
    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}

- (IBAction)getQuoteAction:(id)sender {
    NSString *message;
    if (self.amountTextField.text.doubleValue == 0) {
        message = JFMainLocalizedString(@"exchange.from-amount-not-0");
    }else if (self.amountTextField.text.doubleValue > self.availableVaule.text.doubleValue) {
        message = JFMainLocalizedString(@"exchange.insufficient-fund");
    }
    
    if (message) {
        FZAlertController *vc = [FZAlertController alertControllerWithTitleImage:[UIImage imageNamed:@"prompt_icon"] title:message customView:nil message:nil];
        vc.showCloseBtn = YES;
        FZAlertAction *action = [FZAlertAction actionWithTitle:JFMainLocalizedString(@"exchange.ok") style:UIAlertActionStyleDefault handler:^(FZAlertAction *action) {
                            }];
        [vc addAction:action];
        [self presentViewController:vc animated:YES completion:nil];
    }else {
        DigitalExchangeTradeViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"DigitalExchangeTradeViewController"];
        vc.amount = self.amountTextField.text;
        vc.ccy1 = self.sellLabel.text;
        vc.ccy2 = self.buyLabel.text;
        vc.walletsId = self.walletsId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

@end
